﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Innovative.Atom.Timer.Event
{
	public class AtomEventWrapper
	{
		public event EventHandler<AtomEventTriggeredEventArgs> EventTriggered = null;
		public event EventHandler<AtomExceptionEventArgs> ExceptionOccurred = null;

		private IAtomEvent _atomEvent = null;

		public AtomEventWrapper(IAtomEvent atomEvent)
		{
			this.AtomEvent = atomEvent;
			this.AtomEvent.GetNextTask += AtomEvent_GetNextTask;
		}

		private void AtomEvent_GetNextTask(object sender, AtomGetTaskEventArgs e)
		{
			e.NextTask = new Task<bool>(_EventTriggered);
		}

		private bool _EventTriggered()
		{
			return this.OnEventTriggered(new AtomEventTriggeredEventArgs());
		}

		protected virtual bool OnEventTriggered(AtomEventTriggeredEventArgs e)
		{
			bool returnValue = false;

			if (this.EventTriggered != null)
			{
				try
				{
					this.EventTriggered(this, e);
					returnValue = e.Result;
				}
				catch(Exception ex)
				{
					this.OnExceptionOccurred(new AtomExceptionEventArgs(new AtomTaskExecutionException(ex)));
				}
			}

			return returnValue;
		}

		protected virtual void OnExceptionOccurred(AtomExceptionEventArgs e)
		{
			if (this.ExceptionOccurred != null)
			{
				this.ExceptionOccurred(this, e);
			}
		}

		public IAtomEvent AtomEvent
		{
			get
			{
				return _atomEvent;
			}
			set
			{
				_atomEvent = value;
			}
		}
	}
}
